import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Created by yanli on 16/7/27.
 */
public class FbStatistic {
//    static HostnameVerifier hostnameVerifier = (hostname, session) -> true;

    private static final Logger logger = LoggerFactory.getLogger(FbStatistic.class);

    public FbStatistic(){
    }


    public static void main(String[] args){

        String configPathStr;
        if (args.length == 0){
            configPathStr = System.getProperty("conf", null);
        }else {
            configPathStr = args[0];
        }

        if (StringUtils.isNotBlank(configPathStr)){
            //初始化配置项
            Common.init(configPathStr);
            //初始化系统日志：
            LogManager.init(configPathStr + File.separator + "logback.xml");
            if (logger.isDebugEnabled()){
                logger.debug("初始化配置项成功!");
            }

            long time1 = System.currentTimeMillis();
            FbStatistic fbStatistic;
            //标识是否有获取广告错误
            Boolean isGetAdDataError = false;
            for (JSONObject json : Common.appJson) {
                //记录是否获取数据错误
                Boolean flag = false;
                long date1 = System.currentTimeMillis();
                File file = new File(Common.excelFilePath + File.separator + Common.sinceString + "-" + Common.untilString + File.separator + json.getString("appName"));
                if (file.isDirectory()){
                    continue;
                }
                if(logger.isDebugEnabled()) {
                    logger.debug("正在获取" + json.getString("appName") + "的统计数据,请等待。。。");
                    System.out.println("正在获取" + json.getString("appName") + "的统计数据,请等待。。。");
                }

                //初始化广告类型
                Data.initAdType(json.getString("banner"), json.getString("fullScreen"), json.getString("native"));

                //获取AccessToken
                Common.getAccessToken(json);
                String accessToken = Common.accessToken;

                fbStatistic = new FbStatistic();

                //获取广告统计数据
                if (StringUtils.isNotBlank(accessToken)) {

                    if (logger.isDebugEnabled()){
                        logger.debug("accessToken={}",accessToken);
                        System.out.println("accessToken=" + accessToken);
                    }

                    JSONObject dataOfRequest = fbStatistic.getStatisticData("fb_ad_network_request", "COUNT", json.getString("appId"));//获取广告请求数
                    if (dataOfRequest != null){
                        if (logger.isDebugEnabled()){
                            logger.debug("获取{}广告请求数成功", json.getString("appName"));
                        }
                        Data.me.setCountryDate(dataOfRequest, "request");
                        Data.me.setTimeDate(dataOfRequest, "request");
                    }else {
                        if(logger.isDebugEnabled()) {
                            logger.debug(json.getString("appName") + "获取广告请求数失败!");
                        }
                        isGetAdDataError = true;
                        flag = true;
                    }


                    JSONObject dataOfFill = fbStatistic.getStatisticData("fb_ad_network_request", "SUM",json.getString("appId"));//获取充满广告请求数
                    if (dataOfFill != null){
                        if (logger.isDebugEnabled()){
                            logger.debug("获取{}广告填充数成功", json.getString("appName"));
                        }
                        Data.me.setCountryDate(dataOfFill, "fill");
                        Data.me.setTimeDate(dataOfFill, "fill");
                    }else {
                        if (logger.isDebugEnabled()){
                            logger.debug(json.getString("appName")+"获取广告填充数失败!");
                        }
                        isGetAdDataError = true;
                        flag = true;
                    }


                    JSONObject dataOfImp = fbStatistic.getStatisticData("fb_ad_network_imp", "COUNT", json.getString("appId"));//获取展示次数
                    if (dataOfImp != null){
                        if (logger.isDebugEnabled()){
                            logger.debug("获取{}广告展示次数成功", json.getString("appName"));
                        }
                        Data.me.setCountryDate(dataOfImp, "imp");
                        Data.me.setTimeDate(dataOfImp, "imp");
                    }else {
                        if (logger.isDebugEnabled()){
                            logger.debug(json.getString("appName")+"获取广告展示次数失败!");
                        }
                        isGetAdDataError = true;
                        flag = true;
                    }


                    JSONObject dataOfClick = fbStatistic.getStatisticData("fb_ad_network_click", "COUNT", json.getString("appId"));//获取点击次数
                    if (dataOfClick != null){
                        if (logger.isDebugEnabled()){
                            logger.debug("获取{}广告点击数成功", json.getString("appName"));
                        }
                        Data.me.setCountryDate(dataOfClick, "click");
                        Data.me.setTimeDate(dataOfClick, "click");
                    }else {
                        if (logger.isDebugEnabled()){
                            logger.debug(json.getString("appName")+"获取广告点击次数失败!");
                        }
                        isGetAdDataError = true;
                        flag = true;
                    }


                    JSONObject dataOfRevenue = fbStatistic.getStatisticData("fb_ad_network_revenue", "SUM", json.getString("appId"));//获取预估收入
                    if (dataOfRevenue != null){
                        if (logger.isDebugEnabled()){
                            logger.debug("获取{}广告收入成功", json.getString("appName"));
                        }
                        Data.me.setCountryDate(dataOfRevenue, "revenue");
                        Data.me.setTimeDate(dataOfRevenue, "revenue");
                    }else {
                        if (logger.isDebugEnabled()){
                            logger.debug(json.getString("appName")+"获取广告收入失败!");
                        }
                        isGetAdDataError = true;
                        flag = true;
                    }

                    long date2 = System.currentTimeMillis();
                    if (logger.isDebugEnabled()){
                        logger.debug("耗时:"+(date2-date1)/1000+"秒");
                        System.out.println("耗时:"+(date2-date1)/1000+"秒");
                    }

                    //生成excel文件
                    if (!flag){
                        Data.creatExcel(json.getString("appName"));
                        logger.debug("=================应用"+json.getString("appName")+"生成excel完毕================");
                        System.out.println("=================应用"+json.getString("appName")+"生成excel完毕================");
                    } else {
                        logger.debug("=================应用"+json.getString("appName")+"生成excel失败================");
                        System.out.println("=================应用"+json.getString("appName")+"生成excel失败================");
                    }
                    Data.resetData();
                }else {
                    logger.debug("未找到应用"+ json.getString("appName")+"的access_token");
                    System.out.println("未找到应用"+ json.getString("appName")+"的access_token");
                    isGetAdDataError = true;
                }

            }
            long time2 = System.currentTimeMillis();
            if (logger.isDebugEnabled()){
                logger.debug("总耗时:"+(time2 - time1)/60000+"分钟");
                System.out.println("总耗时:"+(time2 - time1)/60000+"分钟");
            }
            if (isGetAdDataError){
                logger.debug("程序退出!有应用的广告获取异常,部分统计数据未生成成功,请不要改动任何配置重新运行程序!");
                System.out.println("程序退出!有应用的广告获取异常,部分统计数据未生成成功,请不要改动任何配置重新运行程序!");
            }else {
                logger.debug("程序正常退出!统计数据生成成功");
                System.out.println("程序正常退出!统计数据生成成功");
            }
        }else {
            logger.debug("配置路径错误!请检查配置文件");
            return;
        }
    }

    public JSONObject getStatisticData(String event_name, String aggregateBy, String appId){
        String queryUrl = Constants.Url.replace("<APP_ID>", appId).replace("<ACCESS_TOKEN>", Common.accessToken)
                .replace("DATE_OF_SINCE",String.valueOf(Common.getLongTime(Common.sinceString))).replace("DATE_OF_UNTIL", String.valueOf(Common.getLongTime(Common.untilString)))
                .replace("EVENT_NAME", event_name).replace("AGGREGATE_BY", aggregateBy);

        if (logger.isDebugEnabled()){
            logger.debug("广告请求URL={}", queryUrl);
        }
        String result = URLAvailability.getResultFromURL(queryUrl);//获取数据
        if (StringUtils.isNotBlank(result)){
            return JSONObject.parseObject(result);
        }else {
            return null;
        }

    }
}
